package com.wanpinghui.supplier.user;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.oauth.InputInfoActivity;
import com.wanpinghui.supplier.oauth.LoginActivity;
import com.wanpinghui.supplier.oauth.LoginUtil;
import com.wanpinghui.supplier.object.HomePageActivity;
import com.wanpinghui.supplier.widgets.TitlePanelLayoutUser;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.wanpinghui.wphlibrary.model.oauth.UserInfoUtil;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserSetingBean;
import com.wanpinghui.wphlibrary.model.user.UserInfoService;
import com.wanpinghui.wphlibrary.model.user.bean.AreaBean;
import com.wanpinghui.wphlibrary.model.user.bean.BusinessTypeBean;
import com.wanpinghui.wphlibrary.model.user.bean.GetBusinessResult;
import com.wanpinghui.wphlibrary.widgets.ThrottleButton;
import com.yunshl.yunshllibrary.manager.MActivityManager;
import com.yunshl.yunshllibrary.storage.ShareDataManager;
import com.yunshl.yunshllibrary.storage.SharedPreferencesKey;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import retrofit.callback.YRequestCallback;

/**
 * 功能描述
 * author:caitiangui
 * time:2017/11/23
 */

@ContentView(R.layout.layout_activity_business_scope)
public class BusinessScopeActivity extends BaseActivity {

    private int BUSINESSAREA = 100;
    private int BUSINESSTYPE = 101;

    @ViewInject(R.id.ll_business_scope)
    private FrameLayout ll_business_scope;

    @ViewInject(R.id.ll_business_area)
    private FrameLayout ll_business_area;

    @ViewInject(R.id.tpl_title)
    private TitlePanelLayoutUser mLayoutTitle;

    @ViewInject(R.id.tv_business_area)
    private TextView tv_business_area;

    @ViewInject(R.id.tv_business_type)
    private TextView tv_business_type;

    @ViewInject(R.id.btn_submit)
    private ThrottleButton btn_submit;

    private ArrayList<BusinessTypeBean> beanList;
    private ArrayList<AreaBean> areaBeanArrayList;
    private boolean fromLogin;

    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        if (getIntent() != null) {
            fromLogin = getIntent().getBooleanExtra("from_login", false);
        }
        if (!LoginUtil.loginFilter(this)) {
            finish();
        }
        ll_business_scope.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentType = new Intent(BusinessScopeActivity.this, BusinessTypeActivity.class);
                if (beanList != null && beanList.size() > 0) {
                    intentType.putExtra("data", beanList);
                }
                startActivityForResult(intentType, BUSINESSTYPE);
            }
        });
        ll_business_area.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BusinessScopeActivity.this, BusinessAreaActivity.class);
                if (areaBeanArrayList != null && areaBeanArrayList.size() > 0) {
                    intent.putExtra("areaBeanArrayList", areaBeanArrayList);
                }
                startActivityForResult(intent, BUSINESSAREA);
            }
        });
        mLayoutTitle.setOnClickBacktrack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }

    @Override
    public void bindEvents() {
        btn_submit.setOnThrottleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fromLogin) {
                    MActivityManager.getInstance().delACT(HomePageActivity.class);
                    MActivityManager.getInstance().delACT(LoginActivity.class);
                    MActivityManager.getInstance().delACT(InputInfoActivity.class);
                    Intent intent = new Intent(BusinessScopeActivity.this, HomePageActivity.class);
                    intent.putExtra("check", true);
                    startActivity(intent);
                    finish();
                } else {
                    finish();
                }
            }
        });

    }

    @Override
    public void initData() {
        if (fromLogin) {
            mLayoutTitle.hideBack();
            btn_submit.setVisibility(View.VISIBLE);
        } else {
            mLayoutTitle.showBack();
            btn_submit.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        WPHSdk.getService(OAuthService.class).getUserInfoFromS(new YRequestCallback<UserBean>() {
            @Override
            public void onSuccess(UserBean var1) {
                setData();
            }

            @Override
            public void onFailed(int var1, String message) {
                setData();
            }

            @Override
            public void onException(Throwable var1) {
                setData();
            }
        });
    }

    private void setData(){
        WPHSdk.getService(UserInfoService.class).getBusinissData(new YRequestCallback<GetBusinessResult.TagBean>() {
            @Override
            public void onSuccess(GetBusinessResult.TagBean var1) {
                beanList = new ArrayList<>();
                beanList.add(new BusinessTypeBean("install", "安装", var1.isInstall()));
                beanList.add(new BusinessTypeBean("repair", "维修", var1.isRepair()));
                beanList.add(new BusinessTypeBean("rent", "租赁", var1.isRent()));
                beanList.add(new BusinessTypeBean("purchase", "采购", var1.isPurchase()));
                showBusinessType();
            }

            @Override
            public void onFailed(int var1, String message) {

            }

            @Override
            public void onException(Throwable var1) {

            }
        });
        String data = ShareDataManager.getInstance().getPara(SharedPreferencesKey.SELECT_ADDRESS_DATA);
        if (TextUtil.isEmpty(data)) {
            areaBeanArrayList = new Gson().fromJson(getJson(BusinessScopeActivity.this, "prov_city.json"), new TypeToken<List<AreaBean>>() {
            }.getType());
            if (!areaBeanArrayList.get(0).getName().equals("全国都可服务")) {
                AreaBean areaBean = new AreaBean();
                areaBean.setName("全国都可服务");
                areaBean.setSelect(false);
                areaBeanArrayList.add(0, areaBean);
            }

            ShareDataManager.getInstance().save(BusinessScopeActivity.this, SharedPreferencesKey.SELECT_ADDRESS_DATA, new Gson().toJson(areaBeanArrayList));
        } else {
            areaBeanArrayList = new Gson().fromJson(data, new TypeToken<List<AreaBean>>() {}.getType());
            //       setDatas(areaBeanList);
        }
        if (UserInfoUtil.getUserInfo() != null) {
            UserSetingBean setingBean = UserInfoUtil.getUserInfo().getPack();
            List<String> integerList = setingBean.getArea_id();

            if (integerList != null && integerList.size() > 0) {

                for (int i = 1; i < areaBeanArrayList.size(); i++) {

                    for (int x = 0; x < areaBeanArrayList.get(i).getChildren().size(); x++) {

                        String addCode = areaBeanArrayList.get(i).getChildren().get(x).getAdcode();
                        if (integerList.contains(addCode)) {
                            areaBeanArrayList.get(i).getChildren().get(x).setSelect(true);
                        } else {
                            areaBeanArrayList.get(i).getChildren().get(x).setSelect(false);
                        }

                    }
                }
            }
            showBusinessArea();
            // 子类若全选，则父类也选中
            for(int i = 1; i < areaBeanArrayList.size(); i++){
                for (int j = 0; j < areaBeanArrayList.get(i).getChildren().size(); j++){
                    AreaBean areaBean = areaBeanArrayList.get(i).getChildren().get(j);
                    areaBeanArrayList.get(i).setSelect(true);
                    if (!areaBean.isSelect()) {
                        areaBeanArrayList.get(i).setSelect(false);
                    }
                }
            }

        }
    }

    private String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        //获得assets资源管理器
        AssetManager assetManager = context.getAssets();
        //使用IO流读取json文件内容
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName), "utf-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    private void showBusinessType() {
        if (beanList != null && beanList.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (BusinessTypeBean bean : beanList) {
                if (bean.isSelect()) {
                    stringBuilder.append(bean.getName() + " ");
                }
            }
            //      tv_business_type.setText(stringBuilder.toString().substring(0,stringBuilder.toString().length()-1));
            if (stringBuilder.toString().length() > 0) {
                tv_business_type.setText(stringBuilder.toString());
            } else {
                tv_business_type.setText("请选择业务类型");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0) {
            if (requestCode == BUSINESSTYPE) {
                if (data != null) {
                    String string = data.getStringExtra("data");
                    if (string != null) {
                        beanList = new Gson().fromJson(string, new TypeToken<List<BusinessTypeBean>>() {
                        }.getType());
                        showBusinessType();
                    }


                }
            } else if (requestCode == BUSINESSAREA) {
                if (data != null) {
                    areaBeanArrayList = data.getParcelableArrayListExtra("Areabeanlist");
                    showBusinessArea();
                }
            }
        }
    }

    private void showBusinessArea() {
        //   List<AreaBean> areaBeanList  = areaBeanArrayList;
        if (areaBeanArrayList != null && areaBeanArrayList.size() > 0) {
            ArrayList<String> integers = new ArrayList<>();
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < areaBeanArrayList.size(); i++) {
                if (i != 0) {
                    List<AreaBean> areaBean = areaBeanArrayList.get(i).getChildren();
                    for (AreaBean bean : areaBean) {
                        if (bean.isSelect()) {
                            integers.add(bean.getAdcode());
                            stringBuilder.append(bean.getName() + " ");
                        }
                    }
                }
            }
            UserInfoUtil.getUserInfo().getPack().setArea_id(integers);
            if (stringBuilder.toString().length() > 0) {
                tv_business_area.setText(stringBuilder.toString());
            } else {
                tv_business_area.setText("请选择服务区域");
            }

        }
    }
}
